/*
 * emulate.c
 *
 *  Created on: Jan 26, 2013
 *      Author: anhpham
 */

#include "emulate.h"
unsigned char *http[] = {"", "http://www.", "https://www.", "http://", "https://", "tel:", "mailto:"};

bool isSelectCommand(unsigned char* cmd, size_t cmdSize){
	if (cmdSize > 2){
		if ((cmd[0] == (byte_t)0x00) && (cmd[1] == (byte_t) 0xa4)){
			return true;
		}
	}
	return false;
}

bool hex_cmp(unsigned char cmdApdu1[], size_t szcmdApdu1, unsigned char cmdApdu2[], size_t szcmdApdu2){
	if (szcmdApdu1 != szcmdApdu2)
		return false;
	size_t i;
	for (i = 0; i < szcmdApdu1; i++){
		if (cmdApdu1[i] != cmdApdu2[i])
			return false;
	}
	return true;
}

int produceNdefFromURI(char* uri, unsigned char* Ndef){
	int len = 0;
	int i;
	int id = 0;

	//find the id of the uri
	for (i = 1; i < 7; i++){
		if (strstr(uri, http[i]) != NULL){
			id = i;
			break;
		}
	}

	//produce the byte array of the payload
	int payloadLen = strlen(uri) - strlen(http[id]) + 1;
	unsigned char *payload = malloc(payloadLen);
	payload[0] = (byte_t)id;

	for (i = 1; i < payloadLen; i++){
		payload[i] = (byte_t)uri[i + strlen(http[id]) -1];
	}

	//produce the final response
	Ndef[0] = 0x00;
	Ndef[1] = (byte_t)payloadLen + 4;
	Ndef[2] = 0xd1;
	Ndef[3] = 0x01;
	Ndef[4] = (byte_t)payloadLen;
	Ndef[5] = 0x55;

	for(i = 0; i < payloadLen; i++){
		Ndef[6 + i] = payload[i];
	}

	Ndef[6 + i] = 0x90;
	Ndef[7 + i] = 0x00;
	len = i + 8;


	printf("\nNdef message: \n");
	for (i = 0; i < len; i++)
		printf("%02x  ", Ndef[i]);
	printf("\n");

	free(payload);

	return len;
}

void printHex(unsigned char* byteArr, int szArr){
	int i;
	for (i = 0; i < szArr; i++){
		printf("%02x  ", byteArr[i]);
	}
	printf("\n");
}

int produceNdefFromSMS(char* phoneNumber, char* textMessage, unsigned char* Ndef){
	int len = 0;

	//produce byte array of the payload
	//str_payload = "sms:" + phoneNumber + "?body=" + textMessage;
	int payloadLen = strlen("sms:") + strlen(phoneNumber) + strlen("?body=") + strlen(textMessage) + 1;
	printf("payloadLen = %d \n", payloadLen);

	unsigned char payload[MAX_PDU_LEN];

	unsigned char temp[payloadLen];
	strcpy(temp, "sms:");
	strcat(temp, phoneNumber);
	strcat(temp, "?body=");
	strcat(temp, textMessage);

	payload[0] = 0x00;
	int i;
	for (i = 0; i < payloadLen - 1; i++){
		payload[i + 1] = temp[i];
	}

	printf("Payload \n");
	for (i = 0; i < payloadLen; i++){
		printf("%02x ", payload[i]);
	}

	//produce the final response
	Ndef[0] = 0x00;
	Ndef[1] = (byte_t)payloadLen + 4;
	Ndef[2] = 0xd1;
	Ndef[3] = 0x01;
	Ndef[4] = (byte_t)payloadLen;
	Ndef[5] = 0x55;

	for(i = 0; i < payloadLen; i++){
		Ndef[6 + i] = payload[i];
	}

	Ndef[6 + i] = 0x90;
	Ndef[7 + i] = 0x00;
	len = i + 8;

	printf("len = %d \n", len);
	printf("Ndef message: \n");
	for (i = 0; i < len; i++)
		printf("%02x  ", Ndef[i]);
	printf("\n");
	return len;
}


